package com.cdp.web.controller.system;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cdp.common.core.domain.AjaxResult;
import com.cdp.common.core.domain.entity.SysPerformancePredictedModuleHistory;
import com.cdp.common.core.domain.entity.SysPkl;
import com.cdp.common.utils.SecurityUtils;
import com.cdp.system.service.ISysPerformancePredictedModuleHistoryService;
import com.cdp.system.service.ISysPklService;
import com.cdp.system.vo.SysPerformancePredictedModuleHistoryDTO;
import com.cdp.system.vo.SysPerformancePredictedModuleHistoryVO;
import com.cdp.system.vo.SysPklVO;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.security.SecurityUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 性能预测模块地址
 */
@RestController
@RequestMapping
@Slf4j
public class SysPerformancePredictedModuleHistoryController {

    @Autowired
    private ISysPerformancePredictedModuleHistoryService sysPerformancePredictedModuleHistoryService;
    @Autowired
    private ISysPklService sysPklService;


    @Value("${file.excel-mechanical-performance}")
    private String mechanicalPerformanceExcelPath;
    /**
     * 新增性能预测模块历史
     *
     * @param dto
     * @return
     */
    @PostMapping("/savePerformancePredictedModuleHistory")
    public AjaxResult add(@RequestBody SysPerformancePredictedModuleHistoryDTO dto) {
        SysPerformancePredictedModuleHistory history = new SysPerformancePredictedModuleHistory();
        // 从 DTO 设置字段
        history.setUserId(SecurityUtils.getUserId());
        history.setName(dto.getName());
        history.setCreateTime(LocalDateTime.now());
        history.setVersion(1);
        history.setDeleteTime(0);

        // 处理Excel数据
        String excelUrl = null;
        if (dto.getExcelData() != null && !dto.getExcelData().isEmpty()) {
            try {
                // 生成10位文件名（使用UUID的前10个字符）
                // 生成毫秒时间戳后5位+随机数5位的10位文件名
                long timestamp = System.currentTimeMillis();
// 取时间戳的后5位（100000以内）
                String timePart = String.format("%05d", timestamp % 100000);
// 生成5位随机数（10000-99999）
                Random random = new Random();
                String randomPart = String.format("%05d", random.nextInt(90000) + 10000);
// 拼接成10位文件名
                String fileName = timePart + randomPart + ".xlsx";

                // 定义保存目录（根据实际情况修改）
                String uploadDir = mechanicalPerformanceExcelPath;
                File directory = new File(uploadDir);
                if (!directory.exists()) {
                    directory.mkdirs();
                }
                // 创建完整文件路径
                Path filePath = Paths.get(uploadDir, fileName);
                // 写入Excel文件
                try (Workbook workbook = new XSSFWorkbook()) {
                    Sheet sheet = workbook.createSheet("数据");

                    // 创建样式
                    CellStyle headerStyle = workbook.createCellStyle();
                    Font headerFont = workbook.createFont();
                    headerFont.setBold(true);
                    headerStyle.setFont(headerFont);

                    // 写入数据
                    for (int rowIndex = 0; rowIndex < dto.getExcelData().size(); rowIndex++) {
                        Row row = sheet.createRow(rowIndex);
                        List<String> rowData = dto.getExcelData().get(rowIndex);

                        for (int cellIndex = 0; cellIndex < rowData.size(); cellIndex++) {
                            Cell cell = row.createCell(cellIndex);
                            cell.setCellValue(rowData.get(cellIndex));

                            // 设置表头样式
                            if (rowIndex == 0) {
                                cell.setCellStyle(headerStyle);
                            }

                            // 自动调整列宽
                            sheet.autoSizeColumn(cellIndex);
                        }
                    }

                    // 写入文件
                    try (FileOutputStream fos = new FileOutputStream(filePath.toFile())) {
                        workbook.write(fos);
                    }
                }

                // 构建可访问的URL（重点修改！）
                // 原代码: excelUrl = uploadDir + fileName; // 错误：保存了服务器文件路径
                excelUrl = uploadDir + fileName; // 正确：构建相对URL路径

                // 检查URL长度
                if (excelUrl.length() > 255) { // 根据数据库字段长度调整
                    log.warn("Excel URL超过最大长度，截断前: {}", excelUrl);
                    excelUrl = excelUrl.substring(0, 255);
                }

                history.setExcelUrl(excelUrl);
                history.setFilePath(dto.getFilePath()); // 保存物理路径

            } catch (IOException e) {
                log.error("Excel文件生成失败", e);
                return AjaxResult.error("Excel文件生成失败");
            }
        }

        boolean result = sysPerformancePredictedModuleHistoryService.save(history);
        return result ? AjaxResult.success("新增成功") : AjaxResult.error("新增失败");
    }
//    @PostMapping("/savePerformancePredictedModuleHistory")
//    public AjaxResult add(@RequestBody SysPerformancePredictedModuleHistoryDTO dto) {
//        SysPerformancePredictedModuleHistory history = new SysPerformancePredictedModuleHistory();
//        // 从 DTO 设置字段
//        history.setUserId(SecurityUtils.getUserId());
//        history.setName(dto.getName()); // 正确：从传参获取
//        history.setFilePath(dto.getFilePath());
//        history.setCreateTime(LocalDateTime.now());
//        history.setVersion(1);
//        history.setDeleteTime(0);
//        history.setExcelUrl();
//        boolean result = sysPerformancePredictedModuleHistoryService.save(history);
//        return result ? AjaxResult.success("新增成功") : AjaxResult.error("新增失败");
//    }


    /**
     * 查询性能预测模块历史
     *
     * @param dto
     * @return
     */
    @PostMapping("/queryPerformancePredictedModuleHistory")
    public AjaxResult query(@RequestBody SysPerformancePredictedModuleHistoryDTO dto) {

        // 调用服务层
        List<SysPerformancePredictedModuleHistoryVO> historyList = sysPerformancePredictedModuleHistoryService
                .queryPerformancePredictedModuleHistory(dto);


        return AjaxResult.success("查询成功", historyList);
    }


    /**
     * 根据excel地址导出excel
     * @return
     */
    @PostMapping("/explortExcelPerformancePredictedModuleHistoryByUrl")
    public void explortExcelPerformancePredictedModuleHistoryByUrl(@RequestBody SysPerformancePredictedModuleHistoryDTO dto, HttpServletResponse response) {
        String excelUrl = dto.getExcelUrl();

        if (StringUtils.isBlank(excelUrl)) {
            try {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Excel URL不能为空");
            } catch (IOException e) {
                log.error("设置响应错误失败", e);
            }
            return;
        }

        try {
            Path filePath;
            // 直接使用传入的路径（不做任何检查）
            if (excelUrl.startsWith("/api/excel/download/")) {
                // 如果是API路径，从upload目录加载
                String fileName = excelUrl.substring(excelUrl.lastIndexOf('/') + 1);
                filePath = Paths.get(mechanicalPerformanceExcelPath, fileName);
            } else {
                // 否则直接使用传入的路径（无论格式如何）
                filePath = Paths.get(excelUrl);
            }

            File file = filePath.toFile();

            // 仅检查文件是否存在
            if (!file.exists()) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "Excel文件不存在");
                return;
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String fileName = file.getName();
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentLength((int) file.length());

            // 输出文件流
            try (InputStream is = new FileInputStream(file);
                 OutputStream os = response.getOutputStream()) {

                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.flush();
            }
        } catch (Exception e) {
            log.error("导出Excel文件失败", e);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出Excel失败");
            } catch (IOException ex) {
                log.error("设置响应错误失败", ex);
            }
        }
    }

    @GetMapping("/queryPkl")
    public AjaxResult queryPkl() {
        LambdaQueryWrapper<SysPkl> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper
//                .select(SysPkl::getInputFeatures, SysPkl::getRecordName,
//                        SysPkl::getYTest, SysPkl::getYPredFinalTest,
//                        SysPkl::getPklUrl, SysPkl::getId, SysPkl::getXlsxFile)
        queryWrapper.orderByDesc(SysPkl::getCreateTime);

        List<SysPkl> list = sysPklService.list(queryWrapper);


        List<SysPklVO> voList = new ArrayList<>();
        for (SysPkl pkl : list) {
            SysPklVO vo = new SysPklVO();
          BeanUtils.copyProperties(pkl,vo);
            vo.setInputFeatures(pkl.getInputFeatures());
            vo.setRecordName(pkl.getRecordName());
            vo.setPklUrl(pkl.getPklUrl());
            vo.setId(pkl.getId());
            vo.setXlsxFile(pkl.getXlsxFile());
            vo.setInputFeaturesList(parseInputFeatures(pkl.getInputFeatures()));

            try {
                vo.setYTest(parseDoubleList(pkl.getYTest()));
            } catch (Exception e) {
                log.error("解析yTest出错，输入字符串：" + pkl.getYTest(), e);
                return AjaxResult.error("500", "解析yTest出错，输入字符串：" + pkl.getYTest());
            }

            try {
                vo.setYPredFinalTest(parseDoubleList(pkl.getYPredFinalTest()));
            } catch (Exception e) {
                log.error("解析yPredFinalTest出错，输入字符串：" + pkl.getYPredFinalTest(), e);
                return AjaxResult.error("500", "解析yPredFinalTest出错，输入字符串：" + pkl.getYPredFinalTest());
            }

            voList.add(vo);
        }

        return AjaxResult.success("查询成功", voList);
    }

    private List<List<String>> parseExcelData(String json) {
        if (StringUtils.isBlank(json)) {
            return Collections.emptyList();
        }

        List<List> rawList = JSONArray.parseArray(json, List.class);
        List<List<String>> result = new ArrayList<>();

        for (List item : rawList) {
            List<String> subList = new ArrayList<>();
            for (Object obj : item) {
                subList.add(String.valueOf(obj));
            }
            result.add(subList);
        }

        return result;
    }


/*
    @GetMapping("/queryPkl")
    public AjaxResult queryPkl() {
        LambdaQueryWrapper<SysPkl> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .select(SysPkl::getInputFeatures, SysPkl::getRecordName,
                        SysPkl::getYTest, SysPkl::getYPredFinalTest,
                        SysPkl::getPklUrl, SysPkl::getId, SysPkl::getXlsxFile)
                .orderByDesc(SysPkl::getCreateTime);

        List<SysPkl> list = sysPklService.list(queryWrapper);
        if (list.isEmpty()) {
            log.error("查询列表为空");
            return AjaxResult.error("查询列表为空");
        }

        List<SysPklVO> voList = list.stream().map(pkl -> {
            SysPklVO vo = new SysPklVO();
            vo.setInputFeatures(pkl.getInputFeatures());
            vo.setRecordName(pkl.getRecordName());
            vo.setPklUrl(pkl.getPklUrl());
            vo.setId(pkl.getId());
            vo.setXlsxFile(pkl.getXlsxFile());

            vo.setInputFeaturesList(parseInputFeatures(pkl.getInputFeatures()));

            // 解析字符串为List<Double>，加try-catch防止异常
            try {
                vo.setYTest(parseDoubleList(pkl.getYTest()));
            } catch (Exception e) {
                log.error("解析yTest出错，输入字符串：" + pkl.getYTest(), e);

                vo.setYTest(Collections.emptyList());

            }

            try {
                vo.setYPredFinalTest(parseDoubleList(pkl.getYPredFinalTest()));
            } catch (Exception e) {
                log.error("解析yPredFinalTest出错，输入字符串：" + pkl.getYPredFinalTest(), e);
               // vo.setYPredFinalTest(Collections.emptyList());
            }

            return vo;
        }).collect(Collectors.toList());

        return AjaxResult.success("查询成功", voList);
    }
*/


    private List<Double> parseDoubleList(String str) {
        if (str == null || str.isEmpty()) {
            return Collections.emptyList();
        }
        // 去除中括号 [ ]
        str = str.replaceAll("\\[|\\]", "");
        return Arrays.stream(str.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .map(Double::parseDouble)
                .collect(Collectors.toList());
    }


/*
    @GetMapping("/queryPkl")
    public AjaxResult queryPkl() {
        LambdaQueryWrapper<SysPkl> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .select(SysPkl::getInputFeatures, SysPkl::getRecordName,
                        SysPkl::getYTest, SysPkl::getYPredFinalTest,SysPkl::getPklUrl,SysPkl::getId,SysPkl::getXlsxFile)
                .orderByDesc(SysPkl::getCreateTime);

        List<SysPkl> list = sysPklService.list(queryWrapper);
        if (list.isEmpty()) {
            log.error("查询列表为空");
            return AjaxResult.error("查询列表为空");
        }
        // 转成 VO
        List<SysPklVO> voList = list.stream().map(pkl -> {
            SysPklVO vo = new SysPklVO();
            vo.setInputFeatures(pkl.getInputFeatures());
            vo.setRecordName(pkl.getRecordName());
            vo.setYTest(pkl.getYTest());
            vo.setYPredFinalTest(pkl.getYPredFinalTest());
            vo.setPklUrl(pkl.getPklUrl());
            // 解析 inputFeatures 字符串为列表
            String inputFeatures = vo.getInputFeatures();
            vo.setInputFeaturesList(parseInputFeatures(inputFeatures));
            vo.setId(pkl.getId());
            vo.setXlsxFile(pkl.getXlsxFile());

            return vo;
        }).collect(Collectors.toList());

        return AjaxResult.success("查询成功", voList);
    }
*/

    /**
     * 将 inputFeatures 字符串解析为列表
     * 示例输入: "[水泥掺量, CaO含量（%）, SiO2含量（%）, Al2O3含量（%）, 28天抗压强度(MPa)]"
     * 示例输出: ["水泥掺量", "CaO含量（%）", "SiO2含量（%）", "Al2O3含量（%）", "28天抗压强度(MPa)"]
     */
    private List<String> parseInputFeatures(String inputFeatures) {
        if (inputFeatures == null || inputFeatures.trim().isEmpty()) {
            return Collections.emptyList();
        }

        // 移除首尾的方括号
        String content = inputFeatures.trim();
        if (content.startsWith("[") && content.endsWith("]")) {
            content = content.substring(1, content.length() - 1);
        }

        // 使用逗号分隔并去除空格
        return Arrays.stream(content.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());
    }

/*
    @GetMapping("/queryPkl")
    public AjaxResult queryPkl() {
        LambdaQueryWrapper<SysPkl> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .select(SysPkl::getInputFeatures, SysPkl::getRecordName, SysPkl::getYTest, SysPkl::getYPredFinalTest)
                .orderByDesc(SysPkl::getCreateTime);

        List<SysPkl> list = sysPklService.list(queryWrapper);
        if (list.isEmpty()) {
            log.error("查询列表为空");
            return AjaxResult.error("查询列表为空");
        }
        // 转成 VO
        List<SysPklVO> voList = list.stream().map(pkl -> {
            SysPklVO vo = new SysPklVO();
            vo.setInputFeatures(pkl.getInputFeatures());
            vo.setRecordName(pkl.getRecordName());
            vo.setYTest(pkl.getYTest());
            vo.setYPredFinalTest(pkl.getYPredFinalTest());
            String inputFeatures = vo.getInputFeatures();
            vo.setInputFeaturesList();


            return vo;
        }).collect(Collectors.toList());

        return AjaxResult.success("查询成功", voList);
    }*/


//    @PostMapping("/queryPerformancePredictedModuleHistory")
//    public AjaxResult query(@RequestBody SysPerformancePredictedModuleHistoryDTO dto) {
//
//        // 查询数据
//        List<SysPerformancePredictedModuleHistoryVO> historyList = sysPerformancePredictedModuleHistoryService.queryPerformancePredictedModuleHistory(dto);
//
//        if (historyList.isEmpty()) {
//            return AjaxResult.error("没有找到相关记录");
//        }
//
//        return AjaxResult.success("查询成功", historyList);
//    }


}
